package com.meiyuetao.myt.job;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import lab.s2jh.core.pagination.GroupPropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter;
import lab.s2jh.core.pagination.PropertyFilter.MatchType;
import lab.s2jh.core.util.DateUtils;
import lab.s2jh.ctx.DynamicConfigService;
import lab.s2jh.ctx.FreemarkerService;
import lab.s2jh.ctx.MailService;
import lab.s2jh.schedule.BaseQuartzJobBean;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.JobExecutionContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.meiyuetao.myt.sale.entity.BoxOrder;
import com.meiyuetao.myt.sale.entity.BoxOrder.BoxOrderStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.BoxOrderDetailStatusEnum;
import com.meiyuetao.myt.sale.entity.BoxOrderDetail.CommoditiesTypeEnum;
import com.meiyuetao.myt.sale.service.BoxOrderDetailService;
import com.meiyuetao.myt.sale.service.BoxOrderService;

public class IybDailyJob extends BaseQuartzJobBean {
    private final static Logger logger = LoggerFactory.getLogger(IybDailyJob.class);

    @Override
    protected void executeInternalBiz(JobExecutionContext context) {
        logger.debug("BoxOrderAutoConfirmJob executing...");
        DynamicConfigService dynamicConfigService = this.getSpringBean(DynamicConfigService.class);
        BoxOrderService boxOrderService = this.getSpringBean(BoxOrderService.class);
        FreemarkerService freemarkerService = this.getSpringBean(FreemarkerService.class);
        BoxOrderDetailService boxOrderDetailService = this.getSpringBean(BoxOrderDetailService.class);
        // PurchaseCodeService purchaseCodeService =
        // this.getSpringBean(PurchaseCodeService.class);
        // BrandService brandService = this.getSpringBean(BrandService.class);

        Map<String, List<Map<String, String>>> resultMap = new LinkedHashMap<String, List<Map<String, String>>>();
        Map<String, String> resultLittleMap;
        List<Map<String, String>> resultList;

        // 发货提醒

        // 订单、订单行项付款确认提醒

        // 计划进行中，预约发货日期在未来一周内的订单行项客户未付款

        // 品牌授权截止日期到期
        GroupPropertyFilter groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        /*
         * groupPropertyFilter.append(new PropertyFilter(MatchType.EQ,
         * "orderStatus", BoxOrderStatusEnum.S10O));
         * groupPropertyFilter.append(new PropertyFilter(MatchType.LT,
         * "orderTime", new LocalDateTime().minusDays(2) .toDate()));
         * 
         * Calendar endDate = Calendar.getInstance(); endDate.setTime(new
         * Date()); endDate.add(Calendar.DAY_OF_YEAR, 7);
         * groupPropertyFilter.append(new PropertyFilter(MatchType.LT,
         * "endDate", endDate.getTime())); groupPropertyFilter.append(new
         * PropertyFilter(MatchType.NU, "endDate", true)); List<Brand> brands =
         * brandService.findByFilters(groupPropertyFilter); resultList = new
         * ArrayList<Map<String, String>>(); if
         * (CollectionUtils.isNotEmpty(brands)) { for (Brand brand : brands) {
         * resultLittleMap = new LinkedHashMap<String, String>();
         * resultLittleMap.put("品牌名：", brand.getTitle() == null ? "" :
         * brand.getTitle()); resultLittleMap.put("授权开始日期：",
         * brand.getStartDate() == null ? "" :
         * DateUtils.formatDate(brand.getStartDate()));
         * resultLittleMap.put("授权截止日期：", brand.getEndDate() == null ? "" :
         * DateUtils.formatDate(brand.getEndDate()));
         * resultList.add(resultLittleMap);
         * 
         * } } if (resultList.size() > 0) { resultMap.put("品牌授权截止日期到期提醒：",
         * resultList); }
         */
        // 商品价和爬虫商品价偏差大于10%

        // 订单行项自动成功完结处理
        Date now = new Date();
        GroupPropertyFilter orPropertyFilter = GroupPropertyFilter.buildDefaultOrGroupFilter();
        orPropertyFilter.append(new PropertyFilter(MatchType.LT, "autoSuccessTime", now));
        orPropertyFilter.append(new PropertyFilter(MatchType.NU, "autoSuccessTime", Boolean.TRUE));
        groupPropertyFilter.append(orPropertyFilter);
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "orderDetailStatus", BoxOrderDetailStatusEnum.S60R));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "actualSuccessTime", Boolean.TRUE));
        List<BoxOrderDetail> boxOrderDetails = boxOrderDetailService.findByFilters(groupPropertyFilter);
        resultList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(boxOrderDetails)) {
            for (BoxOrderDetail boxOrderDetail : boxOrderDetails) {
                resultLittleMap = new LinkedHashMap<String, String>();
                resultLittleMap.put("订单号/行项号：", boxOrderDetail.getBoxOrder().getOrderSeq() + "." + (boxOrderDetail.getSn() == null ? "无行项号" : boxOrderDetail.getSn()));
                resultLittleMap.put("订单名", boxOrderDetail.getBoxOrder().getTitle() == null ? "" : boxOrderDetail.getBoxOrder().getTitle());
                resultLittleMap.put("订单/行项金额", boxOrderDetail.getPayAmount() == null ? "" : String.valueOf(boxOrderDetail.getPayAmount()));
                resultLittleMap.put("客户：", boxOrderDetail.getCustomerProfile() == null ? "" : (boxOrderDetail.getCustomerProfile().getDisplay() == null ? "客户sid："
                        + boxOrderDetail.getCustomerProfile().getId() : boxOrderDetail.getCustomerProfile().getDisplay()));
                resultLittleMap.put("自动完结时间：", boxOrderDetail.getAutoSuccessTime() == null ? "" : DateUtils.formatDate(boxOrderDetail.getAutoSuccessTime()));
                resultList.add(resultLittleMap);
                boxOrderDetailService.successClose(boxOrderDetail);
            }

        }

        // 订单自动成功完结处理
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(orPropertyFilter);
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "orderStatus", BoxOrderStatusEnum.S60R));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "actualSuccessTime", Boolean.TRUE));
        List<BoxOrder> boxOrders = boxOrderService.findByFilters(groupPropertyFilter);
        if (CollectionUtils.isNotEmpty(boxOrders)) {
            for (BoxOrder boxOrder : boxOrders) {
                resultLittleMap = new LinkedHashMap<String, String>();
                resultLittleMap.put("订单号/行项号：", boxOrder.getOrderSeq());
                resultLittleMap.put("订单名", boxOrder.getTitle() == null ? "" : boxOrder.getTitle());
                resultLittleMap.put("订单/行项金额", boxOrder.getActualPayedAmount() == null ? "" : String.valueOf(boxOrder.getActualPayedAmount()));
                resultLittleMap.put("客户：", boxOrder.getCustomerProfile() == null ? "" : (boxOrder.getCustomerProfile().getDisplay() == null ? "客户sid："
                        + boxOrder.getCustomerProfile().getId() : boxOrder.getCustomerProfile().getDisplay()));
                resultLittleMap.put("自动完结时间：", boxOrder.getAutoSuccessTime() == null ? "" : DateUtils.formatDate(boxOrder.getAutoSuccessTime()));
                resultList.add(resultLittleMap);
                boxOrderService.successClose(boxOrder);
            }
        }
        if (resultList.size() > 0) {
            resultMap.put("订单自动成功完结：", resultList);
        }
        // 订单行项自动收货完成处理
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        String autoRecvDays = dynamicConfigService.getString("cfg.order.auto.recv.days", "10");
        Calendar autoRecvDate = Calendar.getInstance();
        autoRecvDate.add(Calendar.DAY_OF_MONTH, -Integer.valueOf(autoRecvDays));
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "orderDetailStatus", BoxOrderDetailStatusEnum.S50DF));
        groupPropertyFilter.append(new PropertyFilter(MatchType.LT, "deliveryFinishTime", autoRecvDate.getTime()));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "actualConfirmTime", Boolean.TRUE));
        List<BoxOrderDetail> boxOrderDetails2 = boxOrderDetailService.findByFilters(groupPropertyFilter);
        resultList = new ArrayList<Map<String, String>>();
        if (CollectionUtils.isNotEmpty(boxOrderDetails2)) {
            for (BoxOrderDetail boxOrderDetail : boxOrderDetails2) {
                if (boxOrderDetail.getCommoditiesType() != null && !CommoditiesTypeEnum.GOODS.equals(boxOrderDetail.getCommoditiesType())) {
                    /*
                     * filters = PropertyFilter.buildDefaultFilterList();
                     * filters.add(new PropertyFilter(MatchType.EQ,
                     * "boxOrderDetailCommodity.boxOrderDetail",
                     * boxOrderDetail)); filters.add(new
                     * PropertyFilter(MatchType.EQ, "commodity.commodityType",
                     * CommodityTypeEnum.SERVICE)); List<PurchaseCode>
                     * purchaseCodes = purchaseCodeService.find(filters);
                     * Boolean flag = false; for (PurchaseCode purchaseCode :
                     * purchaseCodes) { if
                     * (PurchaseCodeStatusEnum.ENABLE.equals(
                     * purchaseCode.getCodeStatus())) { flag = true; } } if
                     * (!flag) { resultLittleMap = new LinkedHashMap<String,
                     * String>(); resultLittleMap.put("订单号/行项号",
                     * boxOrderDetail.getBoxOrder().getOrderSeq() + "--" +
                     * boxOrderDetail.getSn() == null ? "" :
                     * boxOrderDetail.getSn() == null ? "无行项号" :
                     * boxOrderDetail.getSn()); resultLittleMap.put("订单名",
                     * boxOrderDetail.getBoxOrder().getTitle() == null ? "" :
                     * boxOrderDetail.getBoxOrder().getTitle());
                     * resultLittleMap.put( "自动收货完成时间：",
                     * boxOrderDetail.getActualConfirmTime() == null ? "" :
                     * DateUtil.formatTime(boxOrderDetail
                     * .getActualConfirmTime())); resultLittleMap.put("收货确认操作者",
                     * boxOrderDetail.getActualConfirmOperator() == null ? "" :
                     * boxOrderDetail.getActualConfirmOperator());
                     * resultList.add(resultLittleMap);
                     * boxOrderDetailService.recvConfirm(boxOrderDetail); }
                     */

                } else {
                    resultLittleMap = new LinkedHashMap<String, String>();
                    resultLittleMap.put("订单号/行项号", boxOrderDetail.getBoxOrder().getOrderSeq() + "." + (boxOrderDetail.getSn() == null ? "无行项号" : boxOrderDetail.getSn()));
                    resultLittleMap.put("订单名", boxOrderDetail.getBoxOrder().getTitle() == null ? "" : boxOrderDetail.getBoxOrder().getTitle());
                    resultLittleMap.put("自动收货完成时间：", boxOrderDetail.getActualConfirmTime() == null ? "" : DateUtils.formatTime(boxOrderDetail.getActualConfirmTime()));
                    resultLittleMap.put("收货确认操作者", boxOrderDetail.getActualConfirmOperator() == null ? "" : boxOrderDetail.getActualConfirmOperator());
                    resultList.add(resultLittleMap);
                    boxOrderDetailService.recvConfirm(boxOrderDetail);
                }

            }
        }

        // 订单自动收货完成处理
        groupPropertyFilter = GroupPropertyFilter.buildDefaultAndGroupFilter();
        groupPropertyFilter.append(new PropertyFilter(MatchType.EQ, "orderStatus", BoxOrderStatusEnum.S50DF));
        groupPropertyFilter.append(new PropertyFilter(MatchType.LT, "deliveryFinishTime", autoRecvDate.getTime()));
        groupPropertyFilter.append(new PropertyFilter(MatchType.NU, "actualConfirmTime", Boolean.TRUE));
        List<BoxOrder> boxOrders2 = boxOrderService.findByFilters(groupPropertyFilter);
        if (CollectionUtils.isNotEmpty(boxOrders2)) {
            for (BoxOrder boxOrder : boxOrders2) {
                resultLittleMap = new LinkedHashMap<String, String>();
                resultLittleMap.put("订单号/行项号：", boxOrder.getOrderSeq());
                resultLittleMap.put("订单名", boxOrder.getTitle() == null ? "" : boxOrder.getTitle());
                resultLittleMap.put("自动收货完成时间：", boxOrder.getActualConfirmTime() == null ? "" : DateUtils.formatDate(boxOrder.getActualConfirmTime()));
                resultLittleMap.put("收货确认操作者", boxOrder.getActualConfirmOperator() == null ? "" : boxOrder.getActualConfirmOperator());
                resultList.add(resultLittleMap);
                boxOrderService.recvConfirm(boxOrder);
            }
        }
        if (resultList.size() > 0) {
            resultMap.put("订单行项自动完成收货：", resultList);
        }
        // 发送通知邮件

        String emailHTML = null;
        if (resultMap.size() > 0) {
            String emailToList = dynamicConfigService.getString("cfg.boxOrder.status.email.list", "");
            Map<String, Object> dataMap = new HashMap<String, Object>();
            dataMap.put("resultMap", resultMap);
            Map<String, List<Map<String, String>>> resultMapHourly = new HashMap<String, List<Map<String, String>>>();
            dataMap.put("resultMapHourly", resultMapHourly);
            dataMap.put("fireTime", DateUtils.formatTime(context.getFireTime()));
            emailHTML = freemarkerService.processTemplateByFileName("IYB_ORDER_DAILY_NOTIFY", dataMap);
            if (emailToList != null && StringUtils.isNotBlank(emailHTML)) {
                MailService mailService = this.getSpringBean(MailService.class);
                mailService.sendHtmlMail("日常任务通知", emailHTML, false, emailToList);
            }
        }
        context.setResult(emailHTML);
    }

}
